package com.partner.boot.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.net.URLEncoder;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.partner.boot.common.Constants;
import com.partner.boot.common.annotation.AutoLog;

import com.partner.boot.entity.User;
import com.partner.boot.service.IUserService;
import com.partner.boot.utils.SessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.partner.boot.common.Result;
import org.springframework.web.multipart.MultipartFile;
import com.partner.boot.service.IMessageService;
import com.partner.boot.entity.Message;

import org.springframework.web.bind.annotation.RestController;

/**
* <p>
*  前端控制器
* </p>
*
* @author 小熊
* @since 2023-03-23
*/
@RestController
@RequestMapping("/message")
@Slf4j
public class MessageController {

    @Resource
    private IMessageService messageService;

    @Resource
    IUserService userService;

    @PostMapping
    @SaCheckPermission("message.add")
    @AutoLog("新增聊天信息")
    public Result save(@RequestBody Message[] message) {
        log.info("fromid " + message[0].getFromId() + " toid " + message[0].getToId() + " contents " + message[0].getContents());
        LocalDateTime localDateTime = LocalDateTime.now();
        message[0].setTime(localDateTime);
        messageService.save(message[0]);
        return Result.success();
    }

    @PutMapping
    @SaCheckPermission("message.edit")
    @AutoLog("编辑聊天信息")
    public Result update(@RequestBody Message message) {
        messageService.updateById(message);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @SaCheckPermission("message.delete")
    @AutoLog("删除聊天信息")
    public Result delete(@PathVariable Integer id) {
        messageService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    @SaCheckPermission("message.deleteBatch")
    @AutoLog("批量删除聊天信息")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        messageService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    @SaCheckPermission("message.list")
    public Result findAll() {

        return Result.success(messageService.list());
    }

    @GetMapping("/hot")
    @SaCheckPermission("message.list")
    public Result hot(@RequestParam(defaultValue = "") int fid,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<Message>().orderByAsc("id");
        Page<Message> page = messageService.page(new Page<>(pageNum, pageSize), queryWrapper);

        User dbuser = (User) StpUtil.getSession().get(Constants.LOGIN_USER_KEY);
        List<User> users = userService.list();

        Integer id = dbuser.getId();   // 1  // fid = 2

        // 1 与 2 聊天
        // message表 fromid todi
        //             1      2
        //             2      1

        // 筛选聊天信息
        int count = 0;
        int j=0;
        log.info("total: "+ page.getTotal() + " id: "+id + " ;fid: " + fid);
        for(int i = 0;i<page.getTotal();i++){
            int fromId = page.getRecords().get(i).getFromId();
            int toId = page.getRecords().get(i).getToId();
            log.info("前： fromId :"+ fromId + " toid: "+ toId +  "；---- i: "+ i + "；---- j: " + j + "；----  count "+count+"；----  count+j "+(count+j) );
            // message表的fromid 不为发送方的id 不为接受方的fid
            if( fromId == id && toId == fid){
                j++;
            } else if (fromId == fid && toId == id ) {
                j++;
            } else {
                page.getRecords().remove(page.getRecords().get(i));
                i--;
                count++;
            }

            if (count+j == page.getTotal()){
                break;
            }
        }

        for (Message record : page.getRecords()) {
            users.stream().filter(user -> user.getId().equals(record.getFromId())).findAny().ifPresent(record::setUser);
        }

        return Result.success(page);
    }

    @GetMapping("/{id}")
    @SaCheckPermission("message.list")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(messageService.getById(id));
    }

    @GetMapping("/page")
    @SaCheckPermission("message.list")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<Message>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);

        User currentUser = SessionUtils.getUser();
        String role = currentUser.getRole();
        if ("USER".equals(role)) {  // 用户
            queryWrapper.eq("from_id", currentUser.getId()).or().eq("to_id",currentUser.getId());
            // select * from  dynamic where user_id = xxx

        }

        return Result.success(messageService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    @SaCheckPermission("message.export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Message> list = messageService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Message信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
    * excel 导入
    * @param file
    * @throws Exception
    */
    @PostMapping("/import")
    @SaCheckPermission("message.import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Message> list = reader.readAll(Message.class);

        messageService.saveBatch(list);
        return Result.success();
    }

}
